window.chatapi = {
	getUnreadMessageList: (params, call) => {
		let userId = app.getUserId();
		let url = app.serverUrl + "/message/unread";
		if (!userId) {
			return;
		}
		chatmessagedb.selectCount({
			userId
		}, (data2) => {
			if (data2 != null && data2[0].count == 0) {
				url = app.serverUrl + "/message/all";
			}
			mui.ajax(url, {
				data: {
					userId
				},
				dataType: 'json', //服务器返回json格式数据
				type: 'get', //HTTP请求类型
				timeout: 10000, //超时时间设置为10秒；
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded',
					'auth-token': app.getAuthToken()
				},
				success: function(res) {
					if (res.code == 0) {
						let unreadMessageList = res.data;
						// console.log(JSON.stringify(unreadMessageList))
						if (!unreadMessageList) {
							return;
						}
						let msgIds = unreadMessageList.map(b => b.id);
						// 保存聊天记录和聊天快照到数据库
						chatapi.saveMessageList(unreadMessageList, () => {
							// 对这些未签收的消息，批量签收
							chatapi.signMessage(msgIds, userId);
						});
					}
				},
				error: function(xhr, type, errorThrown) {
					//异常处理；
					app.showToast(type, "error");
				}
			});
		})
		// dictionariesdb.select({
		// 	dict_code: 'update_message_list'
		// }, (data1) => {
		// 	if(data1 != null && data1.length > 0){
		// 		return;
		// 	}
		// })
		// 设置已经加载过聊天记录
		// let dictionaries = {
		// 	create_time: app.formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss'),
		// 	dict_code: 'update_message_list',
		// 	dict_description: '是否已经更新了聊天记录',
		// 	dict_name: '聊天记录更新',
		// 	dict_value: '1',
		// 	status: 1
		// }
		// dictionariesdb.insert(dictionaries, () => {

		// });
	},
	saveMessageList: (unreadMessageList, call) => {
		let userId = app.getUserId();
		if (unreadMessageList.length == 0) {
			if (typeof call === 'function') {
				call();
			}
			return;
		}
		let um = unreadMessageList.shift();
		// 保存聊天历史记录到本地数据库
		let msg = {
			messageId: um.id,
			createTime: um.createTime,
			message: um.message,
			status: 0,
			receiveUserId: um.receiveUserId,
			sendUserId: um.sendUserId,
			type: 1,
			isMyself: um.sendUserId == userId ? 1 : 0
		}
		chatmessagedb.insert(msg, () => {
			// 保存聊天快照记录到本地缓存
			let friendId = um.sendUserId == userId ? um.receiveUserId : um.sendUserId;
			let status = 0;
			chatmessagedb.selectCount({
				userId,
				friendId,
				status
			}, (data3) => {
				msg.unread = data3 == null ? 0 : data3[0].count;
				chatsnapshotmessagedb.insert(msg, () => {
					chatapi.saveMessageList(unreadMessageList, call);
				});
			})
		});
	},
	signMessage: (msgIds, userId) => {
		let url = app.serverUrl + "/message";
		mui.ajax(url, {
			data: msgIds,
			dataType: 'json', //服务器返回json格式数据
			type: 'put', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			headers: {
				'Content-Type': 'application/json',
				'auth-token': app.getAuthToken()
			},
			success: function(res) {
				if (res.code != 0) {
					app.showToast(res.msg, "error");
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				app.showToast(type, "error");
			}
		});
	},
	login: (params, call) => {
		let url = app.serverUrl + "/chat/login";
		// 与后端联调
		mui.ajax(url, {
			data: params,
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			headers: {
				'Content-Type': 'application/json',
				'auth-token': app.getAuthToken()
			},
			success: function(res) {
				//服务器返回响应，根据响应结果，分析是否登录成功；
				if (res.code == 0) {
					// 登录或者注册成功之后，保存全局用户对象到本地缓存
					let user = res.data;
					app.setCacheUser(user);
					if (typeof call === 'function') {
						call();
					}
				} else {
					app.showToast(res.msg, "error");
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				console.log(app.formatDate(new Date()) + ': [error]' + ' ======> [用户登录失败]：' + type);
				app.showToast(type, "error");
			}
		})
	},
	logout: (params, call) => {
		if (!params || params.clientId) {
			if (typeof call === 'function') {
				call();
			}
			return;
		}
		let url = app.serverUrl + "/chat/logout";
		mui.ajax(url, {
			data: {
				clientId: params.clientId
			},
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded',
				'auth-token': app.getAuthToken()
			},
			success: function(res) {
				if (res.code != 0) {
					app.showToast(res.msg, "error");
				} else {
					if (typeof call === 'function') {
						call();
					}
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				app.showToast(type, "error");
			}
		});
	},
	upload: (form, call) => {
		const url = app.serverUrl + '/user/head/upload'
		console.log(app.formatDate(new Date()) + ': [info]' + ' ======> [开始上传头像...] file: ' + form);
		mui.ajax(url, {
			data: form,
			processData: false, // 上传文件时
			contentType: false, // 上传文件时
			dataType: 'json', //服务器返回json格式数据
			type: 'post', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			headers: {
				'auth-token': app.getAuthToken()
			},
			success: function(res) {
				if (res.code != 0) {
					app.showToast(res.msg, "error");
				} else {
					if (typeof call === 'function') {
						call(res.data);
					}
				}
			},
			error: function(xhr, type, errorThrown) {
				//异常处理；
				app.showToast(type, "error");
			}
		});
	}
}
